package day18;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//公平锁和非公平锁
public class Demo2 {
    //有参构造：默认值 flase表示非公平锁，true表示公平锁
    ReentrantLock lock=new ReentrantLock(true);
    //读写锁也是类似的，有参构造（true/false）
    ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock(true);

    public void test(){
        String name=Thread.currentThread().getName();
        lock.lock();  //添加lock互斥锁
        System.out.println(name+"获取了锁，开始执行...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock(); //释放lock互斥锁
            System.out.println(name+"执行结束，开始释放...");
        }
    }
    public static void main(String[] args) {
        Demo2 d=new Demo2();
        for (int i=0;i<5;i++){
            new Thread(()->{
                while (true){
                    d.test();
                }
            },"线程名"+i).start();
        }
    }

}
